package cn.rkylin.oms.warehouse.returnStockin.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.consts.ReturnStockinStatus;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.warehouse.returnStockin.dao.ReturnStockinDAOImpl;
import cn.rkylin.oms.warehouse.returnStockin.dao.ReturnStockinSkuDAOImpl;
import cn.rkylin.oms.warehouse.returnStockin.service.IReturnStockinService;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinSkuVO;
import cn.rkylin.oms.warehouse.returnStockin.vo.ReturnStockinVO;

/**
 * 退货入库单Controller
 * 
 * @author 齐涛
 * @version 1.0
 * @created 28-9-2017 10:51:30
 */
@Controller
@RequestMapping("/returnStockin")
public class ReturnStockinController extends ApolloController {

    private static final Log logger = LogFactory.getLog(ReturnStockinController.class);
    private static final String PAGE_SELECT_STATEMENT = "pageSelectReturnStockin";
    private static final String PAGE_SUK_SELECT_STATEMENT = "selectReturnStockInSkuList";

    @Autowired
    private IReturnStockinService returnStockinServiceImpl;

    @Autowired
    private LogUtil logUtil;

    /**
     * 查询退货入库单列表
     * 
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @param param
     *            退货入库单VO
     * @param start
     *            第几页
     * @param length
     *            每页多少行
     * @return 结果Map
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getReturnStockinList")
    public Map<String, Object> getReturnStockinList(String quickSearch, String formJson, String returnStockinStatus,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length) {
        Map map = new HashMap();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            ReturnStockinVO param = new ReturnStockinVO();
            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(formJson);
            param.setStorId((String) jsonObject.get("storId"));
            param.setShopId((String) jsonObject.get("shopId"));
            param.setKind((String) jsonObject.get("kind"));
            param.setCreateTimeStart((String) jsonObject.get("createTimeStart"));
            param.setCreateTimeEnd((String) jsonObject.get("createTimeEnd"));
            param.setFactInTimeStart((String) jsonObject.get("factInTimeStart"));
            param.setFactInTimeEnd((String) jsonObject.get("factInTimeEnd"));
            param.setFinishTimeStart((String) jsonObject.get("finishTimeStart"));
            param.setFinishTimeEnd((String) jsonObject.get("finishTimeEnd"));
            param.setSkuCode((String) jsonObject.get("skuCode"));
            param.setSkuName((String) jsonObject.get("skuName"));
            param.setGoodsCode((String) jsonObject.get("goodsCode"));
            param.setGoodsName((String) jsonObject.get("goodsName"));
            // 快速查询检索条件
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            if (StringUtils.isNotEmpty(quickSearch)) {
                param.setQuickSearch(quickSearch);
            }
            param.setReturnStockinStatus(returnStockinStatus);
            // 设置项目Id
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            String prjId = currentUser.getCurrentProject().getPrjId();
            param.setPrjId(prjId);

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("enableStatus", "enable");

            // 排序语句生成
            String orderStatement = getOrderString(ReturnStockinDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            PageInfo<ReturnStockinVO> stockInList = returnStockinServiceImpl.findByWhere(page, length, param);
            map.put(JSON_RESULT, SUCCESS);
            map.put(RECORDS_FILTERED, stockInList.getTotal());
            map.put(RECORDS_TOTAL, stockInList.getTotal());
            map.put(RETURN_DATA, stockInList.getList());

        } catch (Exception ex) {
            logUtil.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * 查询退货入库单列表数量
     *
     * @param quickSearch
     *            快速查询条件
     * @param formJson
     *            高级检索条件
     * @param param
     *            退货入库单VO
     * @param start
     *            第几页
     * @param length
     *            每页多少行
     * @return 结果Map
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
    @ResponseBody
    @RequestMapping(value = "/getReturnStockinListCount")
    public Map<String, Object> getReturnStockinListCount(String quickSearch, String formJson, String eturnStockinStatus,
            @RequestParam(required = false, defaultValue = "0") int start, @RequestParam(required = false, defaultValue = "10") int length) {
        Map map = new HashMap();
        try {
            Map waitReceiveMap = this.getReturnStockinList(quickSearch, formJson, ReturnStockinStatus.WAIT_RECEIVE, start, length);
            Map receivingMap = this.getReturnStockinList(quickSearch, formJson, ReturnStockinStatus.RECEIVING, start, length);
            Map completeMap = this.getReturnStockinList(quickSearch, formJson, ReturnStockinStatus.COMPLETE, start, length);
            Map canceledMap = this.getReturnStockinList(quickSearch, formJson, ReturnStockinStatus.CANCELED, start, length);

            map.put(JSON_RESULT, SUCCESS);
            map.put("waitReceiveCount", waitReceiveMap.get(RECORDS_TOTAL));
            map.put("receivingCount", receivingMap.get(RECORDS_TOTAL));
            map.put("completeCount", completeMap.get(RECORDS_TOTAL));
            map.put("canceledCount", canceledMap.get(RECORDS_TOTAL));

        } catch (Exception ex) {
            logUtil.error(ex.getMessage(), ex);
            map.put(JSON_RESULT, FAILED);
            map.put(JSON_MSG, ex.getMessage());
        }

        return map;
    }

    /**
     * 查询退货入库单信息
     *
     * @param stockinId
     *            退货入库单Id
     * @return 结果Map
     * @throws Exception
     *             异常
     */
    @ResponseBody
    @RequestMapping(value = { "/getReturnStockInInfo/{stockinId}" })
    public Map<String, Object> getReturnStockInInfo(@PathVariable String stockinId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            ReturnStockinVO returnStockInVO = new ReturnStockinVO();
            returnStockInVO.setStockinId(stockinId);
            ReturnStockinVO data = returnStockinServiceImpl.getReturnStockinInfo(returnStockInVO);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, data);
        } catch (Exception ex) {
            logUtil.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 查询退货入库单商品列表
     *
     * @param shiporderId
     *            退货入库单Id
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = "/getReturnStockInSkuList")
    public Map<String, Object> getReturnStockInSkuList(String stockinId, String kind) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            ReturnStockinSkuVO returnStockinSkuVO = new ReturnStockinSkuVO();
            returnStockinSkuVO.setStockinId(stockinId);
            returnStockinSkuVO.setKind(kind);
            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            // 排序语句生成
            String orderStatement = getOrderString(ReturnStockinSkuDAOImpl.class.getName(), PAGE_SUK_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                returnStockinSkuVO.setOrderBy(orderStatement);
            }

            List<ReturnStockinSkuVO> returnStockInSkuVOList = returnStockinServiceImpl.selectReturnStockinSkuList(returnStockinSkuVO);

            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RETURN_DATA, returnStockInSkuVOList);
        } catch (Exception ex) {
            logUtil.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }

        return returnMap;
    }

    /**
     * 修改退货入库单
     * 
     * @param returnStockInVO
     *            退货入库单VO
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = "/updateReturnStockIn")
    @SystemControllerLog(module = "退货入库单", operation = "修改退货入库单", keyCode = "stockinId")
    public Map<String, Object> updateReturnStockIn(@RequestBody ReturnStockinVO returnStockinVO) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            returnStockinServiceImpl.updateReturnStockin(returnStockinVO);

            logUtil.info(new DBLog(returnStockinVO.getStockinCode(), "修改退货入库单", "退货入库单管理", "修改成功"));

            returnMap.put(JSON_RESULT, SUCCESS);
        } catch (Exception ex) {
            logUtil.error(new DBLog(returnStockinVO.getStockinCode(), "修改退货入库单", "退货入库单管理", ex.getMessage()));
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("stockinId", returnStockinVO.getStockinId());
        return returnMap;
    }

    /**
     * 取消退货入库单̬
     *
     * @param stockinId
     *            退货入库单Id
     * @return 结果Map
     */
    @ResponseBody
    @RequestMapping(value = { "/cancelReturnStockin/{stockinId}" })
    @SystemControllerLog(module = "退货入库单", operation = "取消退货入库单", keyCode = "stockinId")
    public Map<String, Object> cancelReturnStockin(@PathVariable String stockinId) {
        Map<String, Object> returnMap = new HashMap<String, Object>();

        try {
            Map<String, String> resultMap = returnStockinServiceImpl.cancelReturnStockin(stockinId);

            logUtil.info(new DBLog(stockinId, "取消退货入库单", "退货入库单管理", "取消成功"));

            if ("true".equals(resultMap.get("success"))) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, "取消成功");
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "取消失败");
            }
        } catch (Exception ex) {
            logUtil.error(new DBLog(stockinId, "取消退货入库单", "退货入库单管理", ex.getMessage()));
            logUtil.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        returnMap.put("stockinId", stockinId);
        return returnMap;
    }

}
